<?php
//echo JPATH_BASE.DIRECTORY_SEPARATOR.'autoloader.php';
//echo ' ',JPATH_COMPONENT,' base:',JPATH_BASE,' libs:',JPATH_LIBRARIES,' root:';
$dest = join(DIRECTORY_SEPARATOR,array(JPATH_ROOT,'autoloader.php'));
if(FALSE === file_exists($dest))
    copy(join(DIRECTORY_SEPARATOR,array(JPATH_BASE,'components','com_electroforms','autoloader.php')),
            $dest);
$index = join(DIRECTORY_SEPARATOR,array(JPATH_ROOT,'index.php'));
$contents = file_get_contents($index);
$require = <<<DIFF
<?php
require_once 'autoloader.php';
DIFF;
$fp = fopen($index, 'w');
fwrite($fp, preg_replace('/^<\?(php){0,1}/', $require, $contents));
fclose($fp);

$index = join(DIRECTORY_SEPARATOR,array(JPATH_ROOT,'administrator','index.php'));
$contents = file_get_contents($index);
$require = <<<DIFF
<?php
require_once '../autoloader.php';
DIFF;
$fp = fopen($index, 'w');
fwrite($fp, preg_replace('/^<\?(php){0,1}/', $require, $contents));
fclose($fp);

$script = join(DIRECTORY_SEPARATOR,array(JPATH_ROOT,'libraries','loader.php'));
backup($script);
$contents = file_get_contents($script);
$pattern = '/function __autoload([^}]+}[^}]+})/s';
$replace = "function joomla_autoload$1\nspl_autoload_register('joomla_autoload');";
$fp = fopen($script, 'w');
fwrite($fp, preg_replace($pattern, $replace, $contents));

fclose($fp);
$src = join(DIRECTORY_SEPARATOR,array(JPATH_BASE,'components','com_electroforms','VA'));
$dst = join(DIRECTORY_SEPARATOR,array(JPATH_BASE,'..','libraries','VA'));

//create default file storage dir
@mkdir(join(DIRECTORY_SEPARATOR,array(JPATH_BASE,'components','com_electroforms','files')));

recurse_copy($src, $dst);

function backup($file) {
    copy($file, $file.'.orig');
}

function recurse_copy($src,$dst) {
    $dir = opendir($src);
    @mkdir($dst);
    while(false !== ( $file = readdir($dir)) ) {
        if (( $file != '.' ) && ( $file != '..' )) {
            if ( is_dir($src . '/' . $file) ) {
                recurse_copy($src . '/' . $file,$dst . '/' . $file);
            }
            else {
                copy($src . '/' . $file,$dst . '/' . $file);
            }
        }
    }
    closedir($dir);
}